import { NonDialogCommandForm } from '@app-cad/common/components/command-form';
import { PickInputForFocus } from '@app-cad/common/components/command-form/auto-focus/pick-input';
import { FieldProps, RJSFSchema, UiSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import { Vector3, Vector3Tuple } from 'three-legacy';
import { getDirectionPos } from '../cmd-common/getDirection';
import '../index.scss';
import { DirectionDataType, DirectionType } from '../type';
import { InputNumbersField } from '../cmd-common/input';
import { PickInputValueType } from '@app-base/common/components/pick-input/types';
type DirectionGroupProps = {
  onDirectionSubmit: (data: DirectionDataType) => void; // 回调函数用于将数据传递给父组件
};

function PickInputField({
  formData,
  uiSchema,
  onChange,
}: FieldProps<Vector3Tuple | number[]>) {
  const [pickerData, setPickerData] = useState([]);
  useEffect(() => {
    if (formData?.length === 0) {
      setPickerData([]);
    }
  }, [formData]);

  return (
    <PickInputForFocus
      allowPickType={uiSchema.allowPickType}
      controlled
      autoFocus={uiSchema['ui:autoFocus']}
      value={pickerData}
      onPick={(picked) => {
        setPickerData(picked);
        if (picked?.length > 0) {
          const pos = getDirectionPos(picked);
          if (pos?.length > 0) {
            onChange(pos[0]);
          }
        } else {
          onChange([]);
        }
      }}
      placeholder={pickerData.length === 0 && uiSchema['ui:placeholder']}
    ></PickInputForFocus>
  );
}

export function DirectionGroup({ onDirectionSubmit }: DirectionGroupProps) {
  const [formData, setFormData] = useState(null);

  const schema: RJSFSchema = {
    type: 'object',
    required: ['directionType', 'length'],
    properties: {
      directionType: {
        type: 'number',
        title: '方向类型',
        default: DirectionType.SelectPlane,
        oneOf: [
          {
            const: DirectionType.SelectPlane,
            title: '选择平面',
          },
          {
            const: DirectionType.SelectLine,
            title: '选择直线',
          },
          {
            const: DirectionType.SelectTwoPoint,
            title: '选择两点',
          },
          {
            const: DirectionType.NormalVec,
            title: '单位向量',
          },
        ],
      },
      length: {
        type: 'number',
        title: '长度',
        exclusiveMinimum: 1e-5,
        default: 1,
      },
    },
    allOf: [
      {
        if: {
          properties: {
            directionType: {
              const: DirectionType.SelectPlane,
            },
          },
        },
        then: {
          properties: {
            plane: {
              type: 'array',
              items: { type: 'number' },
            },
          },
        },
      },
      {
        if: {
          properties: {
            directionType: {
              const: DirectionType.SelectLine,
            },
          },
        },
        then: {
          properties: {
            line: {
              type: 'array',
              items: { type: 'number' },
            },
          },
        },
      },
      {
        if: {
          properties: {
            directionType: { const: DirectionType.SelectTwoPoint },
          },
        },
        then: {
          properties: {
            point1: {
              type: 'array',
              items: { type: 'number' },
            },
            point2: {
              type: 'array',
              items: { type: 'number' },
            },
          },
        },
      },
      {
        if: {
          properties: {
            directionType: {
              const: DirectionType.NormalVec,
            },
          },
        },
        then: {
          properties: {
            normalVec: {
              type: 'array',
              items: { type: 'number' },
            },
          },
        },
      },
    ],
  };
  const uiSchema: UiSchema = {
    'ui:submitButtonOptions': {
      norender: true,
    },
    plane: {
      'ui:field': PickInputField,
      'ui:placeholder': '请选择一个平面',
      'ui:autoFocus': true,
      allowPickType: [PickInputValueType.Plane],
    },
    line: {
      'ui:field': PickInputField,
      'ui:placeholder': '请选择一条直线',
      'ui:autoFocus': true,
      allowPickType: [PickInputValueType.Line],
    },
    point1: {
      'ui:field': PickInputField,
      'ui:placeholder': '请选择开始点',
      'ui:autoFocus': true,
      allowPickType: [PickInputValueType.Vertex],
    },
    point2: {
      'ui:field': PickInputField,
      'ui:placeholder': '请选择结束点',
      allowPickType: [PickInputValueType.Vertex],
    },
    normalVec: {
      'ui:field': InputNumbersField,
    },
    'ui:order': [
      'directionType',
      'plane',
      'line',
      'point1',
      'point2',
      'normalVec',
      'length',
    ],
  };
  const onClose = () => {
    setFormData({
      directionType: DirectionType.SelectPlane,
      plane: [],
      line: [],
      point1: [],
      point2: [],
      normalVec: [],
      length: 1,
    });
    onDirectionSubmit({
      directionVisible: false,
      directionText: '请选择方向组件',
      length: null,
    });
  };
  const handleSubmit = () => {
    let vector: Vector3Tuple;
    switch (formData.directionType) {
      case DirectionType.SelectPlane:
        vector = formData.plane;
        break;
      case DirectionType.SelectLine:
        vector = formData.line;
        break;
      case DirectionType.SelectTwoPoint:
        {
          const point1 = new Vector3(...formData.point1);
          const point2 = new Vector3(...formData.point2);
          const directVec = point2.sub(point1);
          vector = directVec.normalize().toArray();
        }
        break;
      case DirectionType.NormalVec:
        vector = formData.normalVec;
        break;
      default:
        break;
    }
    const newVector: Vector3Tuple = vector.map((item) => {
      return item * formData.length;
    }) as Vector3Tuple;
    const toFixedVector = vector.map((item) => {
      return parseFloat(item?.toFixed(4));
    });
    onDirectionSubmit({
      directionVisible: false,
      directionVec: newVector,
      length: formData.length,
      directionText: 'Vec:' + JSON.stringify(toFixedVector),
    });
    setFormData({
      directionType: DirectionType.SelectPlane,
      plane: [],
      line: [],
      point1: [],
      point2: [],
      normalVec: [],
      length: 1,
    });
  };
  const isBtnActive = () => {
    if (!formData) {
      return false;
    }
    switch (formData.directionType) {
      case DirectionType.SelectPlane:
        return formData?.plane?.length > 0;
      case DirectionType.SelectLine:
        return formData?.line?.length > 0;
      case DirectionType.SelectTwoPoint:
        return formData?.point1?.length > 0 && formData?.point2?.length > 0;
      case DirectionType.NormalVec:
        return formData?.normalVec?.length > 0;
      default:
        return false;
    }
  };
  return (
    <>
      <NonDialogCommandForm
        className='direct-form'
        schema={schema}
        extraUiSchema={uiSchema}
        onCancel={onClose}
        formData={formData}
        onChange={(data) => {
          setFormData(data.formData);
        }}
        isFormDataValid={isBtnActive()}
        onSubmit={handleSubmit}
      ></NonDialogCommandForm>
    </>
  );
}
